layui.define(['jquery','form'], function (exports) {
	"use strict";
	var $ = layui.jquery,form=layui.form,object = {
		c: {data:[]}, // 配置项
		f: function (c) { // 数据初始化
			var s=new Date().getTime(),t = this;
			t.c.id = c.id?c.id:'simple_table_choiceshop_cart';
			t.c.tableId = c.tableelem?c.tableelem:'table-'+s;
			//c.data = JSON.parse('[{"accountName":"费玉清","timeTypeName":"00:00~00:59","operatorName":"周杰伦"}]');
			t.c.data = c.data; // 数据
			
			/**自定义的字段**/
			 t.c.discountArr = c.discountArr;
			 t.c.numTotal = 0;
		},
        load:function () { // 加载控件
        	var h = ''
    			+ this.loadTable()
    		+ '';
            $('#'+this.c.id).html(h);
            this.listenBtn();
            this.updateAll();
        },
        loadTable:function () { // 加载表格
            return '<table class="layui-table" style="width: 100%; margin:0;"><thead>'+this.loadTableOfThead()+'</thead><tbody>'+this.loadTableOfTbody()+'</tbody></table>';
        },
        loadTableOfThead:function () { // 加载表头
            var h = '<thead><tr>';
            h += '<th style="text-align:center;">商品编码</th>';
            h += '<th style="text-align:center;">商品名称</th>';
            h += '<th style="text-align:center;">仓库</th>';
            h += '<th style="text-align:center;">单价</th>';
            h += '<th style="text-align:center;">库存</th>';
            h += '<th style="text-align:center;">单箱数量</th>';
            h += '<th style="text-align:center;">起订箱数</th>';
            h += '<th style="text-align:center;">调拨箱数</th>';
            h += '<th style="text-align:center;">调拨数量</th>';
            h += '<th style="text-align:center;">货期</th>';
            h += '<th style="text-align:center;">操作</th>';
            h += '</tr></thead>';
			return h;
        },
        loadTableOfTbody:function () { // 加载表tbody
        	var t = this;
        	var h = '<tbody>';
            for(var i=0;i<t.c.data.length;i++){
	            h += '<tr>';
	            h += '<td style="text-align:center;">' + t.c.data[i].productCode + '</td>';
	            h += '<td style="text-align:center;">' + t.c.data[i].productName + '</td>';
	            h += '<td style="text-align:center;">' + t.c.data[i].warehouse + '</td>';
	            h += '<td style="text-align:center;">' + t.c.data[i].originPrice + '</td>';
	            h += '<td style="text-align:center;">' + t.c.data[i].stock + '</td>';
	            h += '<td style="text-align:center;">' + t.c.data[i].numPerBox + '</td>';
	            h += '<td style="text-align:center;">' + t.c.data[i].numBuyMin + '</td>';
	            h += '<td style="text-align:center;"><input type="number" style="width: 50px; height:27px; border: 0.5px solid #FF5722; text-align: center;" data-index="' + i + '" data-type="numBox" lay-filter="_input"  value="' + t.c.data[i].numBox + '" ></td>';
	            h += '<td style="text-align:center; color: #FF5722; font-weight: 900;">' + t.c.data[i].numAllot + '</td>';
	            h += '<td style="text-align:center; color: #FF5722; font-weight: 900;"><i class="layui-icon layui-icon-tips" style="font-size: 20px; color: #1E9FFF;" data-index="' + i + '" lay-filter="_show_period"></i></td>';
	            h += '<td style="text-align:center; color: #FF5722; font-weight: 900;"><button class="layui-btn layui-btn-xs layui-btn-danger" data-index="' + i + '" lay-filter="_remove_row"><i class="layui-icon" style="color: #ffffff;">&#xe640;</i>删除</button></td>';
                h += '</tr>';
            }
            
            h += '</tbody>';
			return h;
        },
        // 计算总数量
        updateTotalNum: function() {
            var t = this;
			
			/*
			 * 计算总金额，然后计算折扣
			 */
    		var totalNum = 0; // 总金额
            for(var i=0;i<t.c.data.length;i++){
            	totalNum = totalNum + t.c.data[i]['numPerBox'] * (t.c.data[i]['numBox'] == undefined ? 0 : t.c.data[i]['numBox']);
            }
            this.c.totalNum = totalNum;
    		$('#id_total_num').html(totalNum);
        },
        // 计算总金额
        updateTotalPrice: function() {
            var t = this;
			
			/*
			 * 计算总金额，然后计算折扣
			 */
    		var totalPrice = 0; // 总金额
            for(var i=0;i<t.c.data.length;i++){
            	totalPrice = totalPrice + t.c.data[i]['numPerBox'] * (t.c.data[i]['numBox'] == undefined ? 0 : t.c.data[i]['numBox']) * t.c.data[i]['originPrice'];
            }
            this.c.totalPrice = totalPrice;
    		$('#id_total_price').html(totalPrice.toFixed(2));
        },
        // 计算折扣
        updateDiscount: function() {
            var t = this;
            
            var discountArr = t.c.discountArr;
            for(var i = discountArr.length - 1; i >= 0; i--){
            	// 总金额超过满减金额，重新赋值单价和总价
            	if (t.c.totalPrice >= discountArr[i]['amount'] || (i == 0)) {
            		this.c.discount = discountArr[i]['discount'];
    	            break;
				}
            }
    		$('#id_discount').html(this.c.discount * 100 + '%');
        },
        // 计算折后总价
        updateTotalPriceDiscount: function() {
            var t = this;
    		$('#id_total_price_discount').html((t.c.totalPrice * t.c.discount).toFixed(2));
        },
        // 计算每条数据的折后单价和总价
        updateRealPriceOfRow: function() {
            var t = this;
			
            for(var i=0;i<t.c.data.length;i++){
            	var realPrice = t.c.data[i]['originPrice'] * t.c.discount;
            	this.c.data[i]['realPrice'] = realPrice;
            	this.c.data[i]['totalPrice'] = t.c.data[i]['numPerBox'] * (t.c.data[i]['numBox'] == undefined ? 0 : t.c.data[i]['numBox']) * realPrice;
            }
        },
        // 计算总金额、折扣、每条数据折后单价、每条数据折后总价
        updateAll: function() {
        	this.updateTotalNum();
            this.updateTotalPrice();
            this.updateDiscount();
            this.updateTotalPriceDiscount();
            this.updateRealPriceOfRow();
        },
        listenBtn:function () { // 添加监听
            var t = this;
            
			// 监听各个输入框
			$('input[lay-filter="_input"]').on('change',function (e) {
				var index = $(this).attr('data-index');
				var key = $(this).attr('data-type');
				var value = $(this).val();
				
				if (value == '') {
					value == 0;
				}
				if (value * 1 < t.c.data[index]['numBuyMin']) {
					layer.msg('调拨箱数不能少于' + t.c.data[index]['numBuyMin']);
					t.reload(t.c);
					return;
				}
				
				if(key == 'numBox') {
					t.c.data[index]['numAllot'] = value * t.c.data[index]['numPerBox'];
				}
				
				t.c.data[index][key] = value;
				t.reload(t.c);
				
				return;
			});
            
			// 监听货期图标
			$('i[lay-filter="_show_period"]').on('click',function (e) {
				var index = $(this).attr('data-index');
				layer.msg('功能尚未开放');
				return;
				$.ajax({
					type: "POST",
					url: '/api/inter/tpBoutique/getPeriodInfo',
					data: {id: t.c.data[index].id},
					success: function (res) {
						if (res.code == 0) {
							layer.open({
						        area: ['500px', '300px'],
						        fix: false,//不固定
						        offset: 'auto',
						        shade: 0.3,//遮罩
								type: 1,
						        title: '货期信息',
						        shadeClose: true,// 弹层外区域关闭
								content: `<p style="padding:10px; font-size: 18px;">` + res.data.textPeriod + `<br>` + res.data.textArriveTime + `</p>`
							});
						} else {
							layer.msg(res.msg);
						}
					}
				});
			});
            
			// 监听删除按钮
			$('button[lay-filter="_remove_row"]').on('click',function (e) {
				var i = $(this).attr('data-index');
				
	        	layer.confirm('确定删除？', function(index){
					var indexOfLoading = layer.load(1, {
						shade: [0.5,'#000000'] //0.1透明度的白色背景
					});

	                $.post("/api/inter/tpBoutique/removeFromCart", {
	                    cartId: t.c.data[i]['id']
	                }, function (res) {
						layer.close(indexOfLoading);
						layer.close(index);
	    				t.c.data.splice(i, 1);
	    				t.reload(t.c);
	                    layer.msg(res.msg)
	                });
				});
				return;
			});
            
            // 表单控件重新加载
        	form.render();
        },
        reloadTable:function () { // 重新加载表格
            $('#'+this.c.tableId).html(this.loadTable());
            this.listenBtn();
            this.updateAll();
        },
        getData:function () {
            return this.c.data;
        },
        getDataForAllocate:function (vgsbmTo, vgsjcTo) {
        	var t = this;
        	var datas = [];
        	for (var i = 0; i < t.c.data.length; i++) {
        		var data = t.c.data[i];
        		datas.push({
        			vgsbmTo: vgsbmTo,
        			vgsjcTo: vgsjcTo,
        			vgsbmFrom: 'GS0641',
        			vgsjcFrom: '逸思精品',
        			boutiqueGoodsId: data.boutiqueGoodsId,
        			productCode: data.productCode,
        			productName: data.productName,
        			singlePrice: data.realPrice,
        			depotId: data.depotId,
        			depotName: data.warehouse,
        			num: data.numAllot
        		});
			}
            return datas;
        },
        init:function (c) {this.f(c);this.load();return object;},
        reload:function (c) {c.data = this.c.data;$('#' + this.c.id).empty();return this.init(c);},
        reloadData:function () {
        	var t = this;
			$.ajax({
				type: "POST",
				url: '/hr/choiceshop/detailData',
				data: {pcode: t.c.pcode},
				success: function (res) {
					if (res.code == 0) {
						t.c.data = res.data;
						t.reload(t.c);
					} else {
						layer.msg('加载失败，请刷新页面');
					}
				}
			});
        },
        addRow:function (row) {
        	var c = this.c;
        	c.data.push(row);
        	$('#' + c.id).empty();
        	return this.reload(c);
        },
        addRows:function (rows) {
        	var c = this.c;
        	for (var i = 0; i < rows.length; i++) {
	        	c.data.push(rows[i]);
			}
        	$('#' + c.id).empty();
        	return this.reload(c);
        },
        editRow:function (index, row) {
        	var c = this.c;
			c.data[index] = row;
        	$('#' + c.id).empty();
        	return this.reload(c);
        },
        editRowOfAttr:function (index, row) {
        	var c = this.c;
        	for(var key in row){
        		c.data[index][key] = row[key]
        	}
        	$('#' + c.id).empty();
        	return this.reload(c);
        },
        reloadRows:function (rows) {
        	var c = this.c;
        	c.data = rows;
        	return this.reload(c);
        },
        isAbleAllot: function() {
            var t = this;
			
			// 计算总数量
			var numTotal = 0;
            for(var i=0;i<t.c.data.length;i++){
            	numTotal = numTotal + t.c.data[i]['numPerBox'] * (t.c.data[i]['numBox'] == undefined ? 0 : t.c.data[i]['numBox']);
            }
            
            // 判断总数量不能低于最低数量
            var discountArr = t.c.discountArr;
            if (numTotal < discountArr[0]['num']) {
				return false;
			} else {
				return true;
			}
        }
	};
	exports('simple_table_choiceshop_cart', object);
});